package com.hioove.core.filter;

import com.hioove.core.model.base.config.MethodSupport;
import com.hioove.core.web.model.ServletRequest;
import com.hioove.core.web.model.ServletResponse;
import com.hioove.core.web.mvc.route.Route;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 过滤器的实现
 */
public class FilterChain implements IFilter {

    // 程序所有的过滤器
    private List<MethodSupport> filters;

    // 执行的过滤器索引
    private static final ThreadLocal<Integer> INDEX = new ThreadLocal<>();

    // 路由
    private Route route;

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) {

        int idex = getIndex();
        if (idex == Optional.ofNullable(filters).orElseGet(ArrayList::new).size()) {
            // 执行路由
            route.run();
            INDEX.remove();
            return;
        }
        MethodSupport methodSupport = filters.get(idex);
        INDEX.set(idex + 1);
        ((IFilter) methodSupport.getInstance()).doFilter(req, resp, chain);

    }

    public void addFilters(MethodSupport filter) {
        this.filters = Optional.ofNullable(this.filters).orElse(new ArrayList<>());
        this.filters.add(filter);
    }

    public void addRoute(Route route) {
        this.route = route;
    }

    public static int getIndex() {
        return Optional.ofNullable(INDEX.get()).orElse(0);
    }

}
